package cn.wit.summit.chwan.ui.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.IntentDataBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.request.TopicInfoRequest;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.models.response.TopicDetailResponse;
import cn.wit.summit.chwan.net.okhttplib.HttpInfo;
import cn.wit.summit.chwan.net.okhttplib.OkHttpUtil;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.MyImageLoader;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.util.ScrollBoundaryUtil;
import retrofit2.Retrofit;

public class SpecialGameDetailActivity extends BaseActivity {

    @Bind(R.id.bar_title_tx)
    TextView           barTitleTx;
    @Bind(R.id.recyclerView)
    RecyclerView       recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    SimpleDraweeView img;
    TextView         desc;
    private GameAdapter adapter;
    RecyclerView.LayoutManager layoutManager;

    TopicDetailResponse    response = new TopicDetailResponse();
    List<GameListBaseBean> datas    = new ArrayList<>();
    String                 topic_id = "";
    private boolean isCollection;
    private List<JumpBaseBean> topicList = new ArrayList<>();


    private String requestTag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        customHeader = true;
        setContentView(R.layout.activity_special_game_detail);
        ButterKnife.bind(this);
        initApi();
        requestTag = System.currentTimeMillis() + "";

        if (getIntent() != null)
            topic_id = getIntent().getStringExtra("topic_id");
        if (getIntent() != null)
            isCollection = getIntent().getBooleanExtra("isCollection", false);

        barTitleTx.setText("详情");
        initRecyclerView();
        showSkeleton();
    }

    private void initRecyclerView() {
        adapter = new GameAdapter(this, response, datas, topicList);
//        View headerView = LayoutInflater.from(this).inflate(R.layout.header_spacial_game_info, null);
//        img = headerView.findViewById(R.id.img);
//        desc = headerView.findViewById(R.id.desc);
//        recyclerView.addHeaderView(headerView);
//        recyclerView.addFooterView();
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
//        recyclerView.setIAdapter(adapter);
//        recyclerView.setOnRefreshListener(this);
//        recyclerView.setOnLoadMoreListener(this);
//        //刷新加载
//        recyclerView.post(new Runnable() {
//            @Override
//            public void run() {
//                recyclerView.setRefreshing(true);
//            }
//        });recyclerView.addItemDecoration(new MyDecoration(this, getResources().getDrawable(R.drawable.special_game_divider), MyDecoration.VERTICAL_LIST));
        recyclerView.setAdapter(adapter);
        recyclerView.setFocusable(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                SpecialGameDetailActivity.this.onRefresh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                SpecialGameDetailActivity.this.onLoadMore();
            }
        });
        //触发自动刷新
//        refreshLayout.autoRefresh();
        onRefresh();
    }

    //region loadSvr
    int pn = 1, pc = 20;

    void loadSvr() {
        HttpInfo info;
//        if (isCollection)
//            info = BuildRequestUtils.getInstance(this).getCollectionIndex(topic_id, pn, pc);
//        else
//        info = BuildRequestUtils.getInstance(this).getTopicInfo(topic_id, pn, pc);

        TopicInfoRequest request = retrofitManager.getTopicInfo(topic_id, pn, pc);
        api.getTopicInfo(request).enqueue(new MyCallback<ResponseBase<TopicDetailResponse>>() {
            @Override
            public void onSuccess(ResponseBase<TopicDetailResponse> model) {
                if (model != null) {
                    if (model.getCode() == 600)
                        onResponse(model.getData_info());
                    else
                        onFailure(model.getCode(), model.getMsg());
                } else {
                    onFailure(-1, "服务器数据为空！");
                }

            }

            @Override
            public void onFailure(int code, String msg) {
                onFailure(new Exception(msg), code);
            }
//        OkHttpUtil.getDefault().doPostAsync(info
//                , new NetCallBack<>(this, TopicDetailResponse.class, new NetCallBack.Back<TopicDetailResponse>() {//ResponseBase<List<TopAdBean>>
//
//                    @Override
//                    public void onCache(TopicDetailResponse data) {
//                        if (pn == 1) {
//                            datas.clear();
//                            topicList.clear();
//                            response = data;
//                            adapter.setResponse(response);
//                            if (data != null) {
//                                if (data.getCollection_game_list() != null)
//                                    datas.addAll(data.getCollection_game_list());
//                                if (data.getRandom_topic_list() != null)
//                                    topicList.addAll(data.getRandom_topic_list());
//                            }
//                            showHeader();
//                            adapter.clearDownloadStatus();
//                            adapter.notifyDataSetChanged();
//                        }
//                    }

            public void onResponse(TopicDetailResponse data) {
                cancelLoadingFinish();
                if (pn == 1) {
                    datas.clear();
                    topicList.clear();
                    response = data;
                    adapter.setResponse(response);
                }
                if (data != null) {
                    if (data.getCollection_game_list() != null)
                        datas.addAll(data.getCollection_game_list());
                    if (data.getRandom_topic_list() != null)
                        topicList.addAll(data.getRandom_topic_list());
                }
                showHeader();
                if (data == null || data.getCollection_game_list() == null || data.getCollection_game_list().size() == 0) {
                    if (adapter != null) {
                        adapter.setShowFooter(true);
                    }
                    stopLoading(true);
                } else {
                    stopLoading();
                    pn++;
                    if (pn == 2 && refreshLayout!=null && refreshLayout.getLayout()!=null) {
                        refreshLayout.getLayout().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (!ScrollBoundaryUtil.canScrollDown(recyclerView)) {
                                    onLoadMore();
                                }
                            }
                        },20);
                    }

                }

            }

            private void showHeader() {
                if (response != null) {
//                            MyImageLoader.load(img, response.getCollection_cover_pic());
//                            desc.setText(response.getCollection_info());
                }
            }

            public void onFailure(Exception e, int code) {
                cancelLoadingError();
                stopLoading();
                showToast(e.getMessage());
            }
        });
    }

    private void stopLoading(boolean noMore) {
        refreshLayout.finishRefresh();
        if (noMore) {
            refreshLayout.setNoMoreData(true);
            refreshLayout.finishLoadMoreWithNoMoreData();
        }
        else
            refreshLayout.finishLoadMore();
        adapter.clearDownloadStatus();
        adapter.notifyDataSetChanged();
        hideSkeleton();
    }

    private void stopLoading() {
        stopLoading(false);
    }

    public void onRefresh() {
        refreshLayout.setNoMoreData(false);
        pn = 1;
        if (adapter != null)
            adapter.setShowFooter(false);
        loadSvr();
    }

    public void onLoadMore() {
        loadSvr();
    }

    //endregion

    private class GameAdapter extends RecyclerView.Adapter {
        private final List<JumpBaseBean> topicList;

        public void setResponse(TopicDetailResponse response) {
            this.response = response;
        }

        private TopicDetailResponse    response;
        private List<GameListBaseBean> datas;
        Activity context;

        private boolean showHeader = true;
        private boolean showFooter = false;

        public void setShowHeader(boolean showHeader) {
            this.showHeader = showHeader;
        }

        public void setShowFooter(boolean showFooter) {
            this.showFooter = showFooter;
        }

        public GameAdapter(Activity context, TopicDetailResponse response, List<GameListBaseBean> datas, List<JumpBaseBean> topicList) {
            this.context = context;
            this.response = response;
            this.datas = datas;
            this.topicList = topicList;
        }

        private class TitleVH extends RecyclerView.ViewHolder {
            TextView title;
            TextView moreText;
            View     more;

            public TitleVH(View inflate) {
                super(inflate);
                title = inflate.findViewById(R.id.title);
                moreText = inflate.findViewById(R.id.moreText);
                more = inflate.findViewById(R.id.more);
                if (more.getVisibility() == View.GONE) {
                    more.setVisibility(View.VISIBLE);
                }
            }
        }

        private class ChoicePicVH extends RecyclerView.ViewHolder {
            public SimpleDraweeView img;

            public ChoicePicVH(View inflate) {
                super(inflate);
                img = inflate.findViewById(R.id.img);
            }
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if (viewType == 1) {
                return new ItemHeader(LayoutInflater.from(context).inflate(R.layout.header_spacial_game_info, parent, false));
            } else if (viewType == 2) {
                return new ItemFooter(LayoutInflater.from(context).inflate(R.layout.header_spacial_more, parent, false));
            } else if (viewType == 3) {
                return new ChoicePicVH(LayoutInflater.from(context).inflate(R.layout.item_choice_pic, parent, false));
            } else if (viewType == 4) {
                return new TitleVH(LayoutInflater.from(context).inflate(R.layout.find_fragment_title_item, parent, false));
            } else if (viewType == 0)
                return new ImgVH(LayoutInflater.from(context).inflate(R.layout.item_special_game, parent, false));

            return null;
        }

        //region Download Game
        private Map<String, String> downTemp = new HashMap<>();

        public void clearDownloadStatus() {
            downTemp.clear();
        }

        public String getPoByGameId(String gameId) {
            String result = "";
            if (downTemp.size() > 0 && downTemp.containsKey(gameId)) {
                result = downTemp.get(gameId);
            }
            return result;
        }

        public GameListBaseBean getBeanData(int itemPo, int po) {
            if (getItemViewType(itemPo) == 0) {
                GameListBaseBean list = (GameListBaseBean) getItem(itemPo);
                return list;
            }
            return null;
        }
        //endregion

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            try {
                if (holder == null) return;
                if (getItemViewType(position) == 1) {
                    ItemHeader header = (ItemHeader) holder;
                    if (response != null) {
                        if (TextUtils.isEmpty(response.getCollection_cover_pic())) {
                            header.img.setVisibility(View.GONE);
                        } else {
                            header.img.setVisibility(View.VISIBLE);
                            MyImageLoader.load(header.img, response.getCollection_cover_pic());
                        }
                        if (TextUtils.isEmpty(response.getCollection_info())) {
                            header.desc.setVisibility(View.GONE);
                        } else {
                            header.desc.setVisibility(View.VISIBLE);
                            header.desc.setText(response.getCollection_info());
                        }
                    } else {
                        header.img.setVisibility(View.GONE);
                        header.desc.setVisibility(View.GONE);
                    }
                    return;
                } else if (getItemViewType(position) == 2) {
                    ItemFooter footer = (ItemFooter) holder;
                    footer.more.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            IntentDataBean bean = new IntentDataBean();
                            bean.setJump_link_type(3);
                            bean.setJump_type(9);
                            IntentUtil.getInstance().intentTo(SpecialGameDetailActivity.this, bean);
                        }
                    });
                    return;
                } else if (getItemViewType(position) == 0) {
                    GameListBaseBean gameListBaseBean = (GameListBaseBean) getItem(position);
                    if (gameListBaseBean == null) return;
                    ((ImgVH) holder).listItem.setData(context, gameListBaseBean);
                    downTemp.put(gameListBaseBean.getGame_id(), position + "");
                } else if (getItemViewType(position) == 3) {
                    onBindChoicePicViewHolder((ChoicePicVH) holder, position);
                } else if (getItemViewType(position) == 4) {
                    onBindTitleViewHolder((TitleVH) holder, position);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void onBindChoicePicViewHolder(ChoicePicVH holder, int position) {
            final JumpBaseBean jumpBaseBean = (JumpBaseBean) getItem(position);
            MyImageLoader.load(holder.img, jumpBaseBean.getJump_cover_big_pic(), MyImageLoader.makeRoundParams(context, context.getResources().getDimensionPixelOffset(R.dimen.wdp10)));

            holder.img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    IntentUtil.getInstance().intentTo(mAty, jumpBaseBean);
                }
            });
        }

        private void onBindTitleViewHolder(TitleVH holder, int position) {
            final JumpBaseBean jumpBaseBean = (JumpBaseBean) getItem(position);
            holder.title.setText("推荐专题");
            holder.more.setVisibility(View.GONE);
            if (jumpBaseBean == null) return;
            holder.title.setText(jumpBaseBean.getJump_sub_title());
            if (!TextUtils.isEmpty(jumpBaseBean.getJump_label()))
                holder.moreText.setText(jumpBaseBean.getJump_label());
            else holder.moreText.setText("全部");
            if (jumpBaseBean.getJump_info() == null) {
                holder.more.setVisibility(View.GONE);
            } else {
                holder.more.setVisibility(View.VISIBLE);
                holder.more.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        IntentUtil.getInstance().intentTo(mAty, jumpBaseBean);
                    }
                });
            }
        }

        public Object getItem(int position) {
            if (getItemViewType(position) == 0) {
                return datas.get(getIndex(position));
            } else if (getItemViewType(position) == 3) {
                return topicList.get(getIndex(position));
            }
            return null;
        }

        @Override
        public int getItemViewType(int position) {
            int index = position;
            if (showHeader && index == 0) return 1;
            if (showHeader) index--;
            if (datas != null && datas.size() > 0
                    && index >= 0 && index < datas.size()) return 0;
            index -= datas.size();
            if (topicList != null && topicList.size() > 0) {
                if (index == 0) return 4;
                index--;
                if (index >= 0 && index < topicList.size())
                    return 3;
                index -= topicList.size();
            }
            if (showFooter && index == 0) return 2;
            return -1;
        }

        public int getIndex(int position) {
            int index = position;
            if (showHeader && index == 0) return index;
            if (showHeader) index--;
            if (datas != null && datas.size() > 0
                    && index >= 0 && index < datas.size()) return index;
            index -= datas.size();
            if (topicList != null && topicList.size() > 0) {
                if (index == 0) return index;
                index--;
                if (index >= 0 && index < topicList.size())
                    return index;
                index -= topicList.size();
            }
            if (showFooter && index == 0) return index;
            return index;
        }

        @Override
        public int getItemCount() {
            int ret = 0;
            if (datas == null) return ret;
            ret += datas.size();
            if (showHeader) ret++;
            if (showFooter) ret++;
            if (topicList != null && topicList.size() > 0) ret += topicList.size() + 1;
            return ret;
        }

        private class ItemHeader extends RecyclerView.ViewHolder {

            public SimpleDraweeView img;
            public TextView         desc;

            public ItemHeader(View itemView) {
                super(itemView);
                img = itemView.findViewById(R.id.img);
                desc = itemView.findViewById(R.id.desc);
            }
        }

        private class ItemFooter extends RecyclerView.ViewHolder {

            public View more;

            public ItemFooter(View itemView) {
                super(itemView);
                more = itemView.findViewById(R.id.more);
            }
        }

        private class ImgVH extends RecyclerView.ViewHolder {
            public ItemListView listItem;

            public ImgVH(View inflate) {
                super(inflate);
                listItem = inflate.findViewById(R.id.listItem);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!TextUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View         view     = layoutManager.findViewByPosition(Integer.valueOf(str));
            ItemListView itemView = view.findViewById(R.id.listItem);
            if (itemView == null) {
                return;
            }
            DownloadViewStroke dowView = itemView.getDownView();
            dowView.updateButn(table);
        }

        super.onEventMainThread(downloadEvent);
    }

    @OnClick(R.id.back)
    void back() {
        finish();
    }

    @Override
    public void reGetData() {
        if (NetWorkUtils.isNetworkConnected(this))
            onRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (datas != null && datas.size() > 0
                && !notNetEvent.isHasNet) return;
        super.onEventMainThread(notNetEvent);
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_special_game_detail_skeleton;
    }

    @Override
    protected void onDestroy() {
        OkHttpUtil.getDefault().cancelRequest(requestTag);
        super.onDestroy();
    }

    //region Retrofit
    private RetrofitManager retrofitManager;
    private Retrofit        retrofit;
    private ApiUtil         api;

    void initApi() {
        if (retrofitManager == null) {
            retrofitManager = RetrofitManager.getInstance(this);
            retrofit = retrofitManager.getRetrofit();
            api = retrofit.create(ApiUtil.class);
        }
    }
    //endregion
}
